Page({
  data: {
    currentService: {
      id: 'SF20250729001',
      type: '快递配送服务',
      progress: 66,
      status: '配送中',
      workerName: '张三',
      workerPhone: '13800138000',
      estimatedCompletion: '2025-07-29 18:00'
    },
    historyList: [
      {
        id: 'SF20250728001',
        type: '快递代收服务',
        status: 'completed',
        statusText: '已完成',
        date: '2025-07-28 14:30',
        details: '物品：文件，数量：1',
        rating: 5,
        comment: '服务很及时，师傅态度很好'
      },
      {
        id: 'SF20250725001',
        type: '包裹配送服务',
        status: 'completed',
        statusText: '已完成',
        date: '2025-07-25 09:15',
        details: '物品：电子产品，数量：1',
        rating: 4,
        comment: '包裹完好，配送及时'
      },
      {
        id: 'SF20250720001',
        type: '生鲜配送服务',
        status: 'cancelled',
        statusText: '已取消',
        date: '2025-07-20 16:45',
        details: '物品：水果，数量：1箱',
        rating: 0,
        comment: ''
      },
      {
        id: 'SF20250715001',
        type: '家具配送服务',
        status: 'cancelled',
        statusText: '已取消',
        date: '2025-07-15 11:20',
        details: '物品：椅子，数量：2把',
        rating: 0,
        comment: ''
      }
    ],
    filteredHistory: [],
    activeFilter: 'all',
    showModal: false,
    modalTitle: '',
    modalMessage: '',
    showConfirmationModal: false
  },

  onLoad() {
    // 初始化筛选历史记录
    this.setData({
      filteredHistory: this.data.historyList
    });

    // 模拟状态更新推送
    setTimeout(() => {
      this.showModal('服务更新', '您有一个服务正在配送中，请注意查收');
    }, 5000);
  },

  // 刷新当前服务状态
  refreshStatus() {
    wx.showLoading({
      title: '刷新中...',
    });

    // 模拟异步请求后端获取最新状态
    setTimeout(() => {
      const currentService = this.data.currentService;
      const newProgress = Math.min(currentService.progress + Math.floor(Math.random() * 15), 100);
      const newStatus = newProgress === 100 ? '已完成' : '配送中';

      this.setData({
        currentService: {
          ...currentService,
          progress: newProgress,
          status: newStatus
        }
      });

      wx.hideLoading();
      this.showModal('状态更新', `服务进度已更新至${newProgress}%，当前状态：${newStatus}`);

      // 如果服务已完成，显示确认弹窗
      if (newProgress === 100) {
        setTimeout(() => {
          this.setData({
            showConfirmationModal: true
          });
        }, 1000);
      }
    }, 1000);
  },

  // 刷新历史记录
  refreshHistory() {
    wx.showLoading({
      title: '刷新中...',
    });

    // 模拟异步请求后端获取最新历史记录
    setTimeout(() => {
      const newItem = {
        id: 'SF' + new Date().getTime().toString().substr(0, 8),
        type: '紧急文件配送',
        status: 'completed',
        statusText: '已完成',
        date: new Date().toLocaleString(),
        details: '物品：合同，数量：1'
      };

      const newHistoryList = [newItem, ...this.data.historyList];
      this.setData({
        historyList: newHistoryList,
        filteredHistory: this.filterHistoryList(newHistoryList, this.data.activeFilter)
      });

      wx.hideLoading();
      this.showModal('更新成功', '历史服务记录已更新');
    }, 1000);
  },

  // 筛选历史记录
  filterHistory(e) {
    const type = e.currentTarget.dataset.type;
    const filteredList = this.filterHistoryList(this.data.historyList, type);

    this.setData({
      activeFilter: type,
      filteredHistory: filteredList
    });
  },

  // 筛选历史记录列表
  filterHistoryList(list, type) {
    if (type === 'all') {
      return list;
    } else {
      return list.filter(item => item.status === type);
    }
  },

  // 查看历史记录详情
  viewHistoryDetail(e) {
    const id = e.currentTarget.dataset.id;
    const item = this.data.historyList.find(item => item.id === id);
    if (item) {
      let feedbackInfo = '';
      if (item.status === 'completed' && item.rating > 0) {
        feedbackInfo = `\n\n反馈评分：${'★'.repeat(item.rating)}${'☆'.repeat(5-item.rating)}\n反馈内容：${item.comment}`;
      } else if (item.status === 'completed') {
        feedbackInfo = '\n\n暂无反馈信息，您可以添加反馈';
      }
      this.showModal('服务详情', `订单号：${item.id}\n类型：${item.type}\n状态：${item.statusText}\n日期：${item.date}\n详情：${item.details}${feedbackInfo}`);
    }
  },

  // 联系师傅
  callWorker() {
    wx.showModal({
      title: '联系师傅',
      content: `是否拨打 ${this.data.currentService.workerPhone} 联系 ${this.data.currentService.workerName}？`,
      success: (res) => {
        if (res.confirm) {
          // 实际应用中可以调用wx.makePhoneCall
          this.showModal('拨打成功', `正在拨打 ${this.data.currentService.workerPhone}`);
        }
      }
    });
  },

  // 申请新服务
  requestNewService() {
    wx.navigateTo({
      url: '/pages/appointment/appointment' // 请根据实际预约服务页面路径调整
    });
  },

  // 联系客服
  contactCustomerService() {
    wx.navigateTo({
      url: '/pages/customer-service/customer-service'
    })
  },

  // 确认服务
  confirmService(e) {
    const received = e.currentTarget.dataset.received;
    this.setData({
      showConfirmationModal: false
    });

    if (received) {
      this.showModal('确认成功', '感谢您的确认，我们已记录您已收到服务');
    } else {
      this.showModal('确认失败', '我们将尽快联系您处理问题');
    }
  },

  // 显示弹窗
  showModal(title, message) {
    this.setData({
      showModal: true,
      modalTitle: title,
      modalMessage: message
    });
  },

  // 关闭弹窗
  closeModal() {
    this.setData({
      showModal: false
    });
  }
});